package com.rem.resources;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author Rem
 * @date 2023-03-07
 */
public class ResourceDemo {

    public static void main(String[] args) throws IOException {
        /**
         * 读取网络资源
         * 读取根目录下资源 file 前缀
         */
        //internetResource("https://www.baidu.com");
        //internetResource("file:my1.txt");
        /**
         * 读取classPath下资源
         */
        //loadClassPathResource("jdbc.properties");

        /**
         * 读取根目录下资源
         */
        // loadFileResource("my1.txt");

    }

    /**
     * 访问网络资源
     */
    private static void internetResource(String path) {

        // 创建一个 Resource 对象
        Resource url;
        try {
            url = new UrlResource(path);
            // 获取资源名
            System.out.println(url.getFilename());
            System.out.println(url.getURI());
            // 获取资源描述
            System.out.println(url.getDescription());
            //获取资源内容
            System.out.println(url.getInputStream().read());

            byte[] bytes = url.getInputStream().readAllBytes();

            String s = new String(bytes, StandardCharsets.UTF_8);
            System.out.println(s);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * classPath下
     *
     * @param path
     */
    public static void loadClassPathResource(String path) {
        // 创建一个 Resource 对象
        Resource resource = new ClassPathResource(path);
        // 获取文件名
        System.out.println("resource.getFileName = " + resource.getFilename());
        // 获取文件描述
        System.out.println("resource.getDescription = " + resource.getDescription());
        //获取文件内容
        try (InputStream in = resource.getInputStream()) {
            byte[] b = new byte[1024];
            while (in.read(b) != -1) {
                System.out.println(new String(b));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 根目录下
     *
     * @param path
     */
    public static void loadFileResource(String path) {
        //创建对象
        Resource resource = new FileSystemResource(path);

        System.out.println(resource.getFilename());
        System.out.println(resource.getDescription());
        try {
            InputStream in = resource.getInputStream();
            byte[] b = new byte[1024];
            while (in.read(b) != -1) {
                System.out.println(new String(b));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
